package com.atguigu.flink.day02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2023/12/1
 * 该案例演示了并行度的设置
 *  并行度：一个算子并行子任务的个数称之为并行度
 *  如果设置：
 *      代码中单独指定算子并行度 > 代码中进行全局的设置  > 在提交命令中设置 > flink-conf.xml配置文件中设置
 *
 */
public class Flink01_par {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        // StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        Configuration conf = new Configuration();
        conf.set(RestOptions.BIND_PORT,"8081");
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);

        //全局设置并行度 默认：cpu的线程数
        env.setParallelism(1);
        //TODO 2.从指定的网络端口读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 3.对读取的数据进行转换 封装为一个Tuple2
        SingleOutputStreamOperator<String> flapMapDS = socketDS.flatMap(
            new FlatMapFunction<String, String>() {
                @Override
                public void flatMap(String lineStr, Collector<String> out) throws Exception {
                    String[] wordArr = lineStr.split(" ");
                    for (String word : wordArr) {
                        out.collect(word);
                    }
                }
            }
        );
        SingleOutputStreamOperator<Tuple2<String, Long>> tupleDS = flapMapDS.map(
            new MapFunction<String, Tuple2<String, Long>>() {
                @Override
                public Tuple2<String, Long> map(String word) throws Exception {
                    return Tuple2.of(word, 1L);
                }
            }
        );
        //TODO 4.按照单词分组
        KeyedStream<Tuple2<String, Long>, Tuple> keyedDS = tupleDS.keyBy(0);
        //TODO 5.聚合
        SingleOutputStreamOperator<Tuple2<String, Long>> sumDS = keyedDS.sum(1);
        //TODO 6.打印
        sumDS.print();

        env.execute();
    }
}
